<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--小区数据-->
            <el-col :span="24" :xs="24">
                <el-card class="box-card">
                    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                        label-width="68px">
                        <el-form-item label="计划名称" prop="planName">
                            <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="安检员" prop="checkerName">
                            <el-input v-model="queryParams.checkerName" placeholder="请输入安检员" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="计划状态" prop="planStatus">
                            <el-select v-model="queryParams.planStatus" filterable placeholder="请选择计划状态"
                                style="width:150px">
                                <el-option label="已登记" value="1"> </el-option>
                                <el-option label="已下发" value="2"> </el-option>
                                <el-option label="已关闭" value="3"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>

                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                                v-hasPermi="['system:checkplan:add']">新增</el-button>
                        </el-col>
                        <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                  v-hasPermi="['fileManagement:areaDefinition:edit']">修改</el-button>
              </el-col> -->
                        <!-- <el-col :span="1.5">
                            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                                @click="handleDelete('批量')"
                                v-hasPermi="['fileManagement:areaDefinition:remove']">删除</el-button>
                        </el-col> -->
                        <!-- <el-col :span="1.5">
                            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport('下发')"
                                v-hasPermi="['fileManagement:areaDefinition:import']">下发</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleImport('关闭')"
                                v-hasPermi="['fileManagement:areaDefinition:export']">关闭</el-button>
                        </el-col> -->
                        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                    </el-row>

                    <el-table v-loading="loading" :data="userList" border @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column label="计划名称" align="center" key="planName" prop="planName" />
                        <el-table-column label="计划状态" align="center" key="planStatus" prop="planStatus"
                            :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <span v-if="scope.row.planStatus == '1'">已登记</span>
                                <span v-if="scope.row.planStatus == '2'">已下发</span>
                                <span v-if="scope.row.planStatus == '3'">已关闭</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="计划开始时间" align="center" key="startTime" prop="startTime"
                            :show-overflow-tooltip="true" width="150" />
                        <el-table-column label="计划结束时间" align="center" key="stopTime" prop="stopTime"
                            :show-overflow-tooltip="true" width="150" />
                        <el-table-column prop="customerType" label="客户类型" width="80">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.customer_type" :value="scope.row.customerType" />
                            </template>
                        </el-table-column>
                        <el-table-column label="用户总数(户)" align="center" key="customerCount" prop="customerCount"
                            :show-overflow-tooltip="true" width="150" />
                        <el-table-column label="入户数(户)" align="center" key="enterHomeCount" prop="enterHomeCount"
                            :show-overflow-tooltip="true" width="150" />
                        <el-table-column label="安检员" align="center" key="checkerName" prop="checkerName"
                            :show-overflow-tooltip="true" />
                        <!-- <el-table-column label="制定时间" align="center" key="6" prop="6" :show-overflow-tooltip="true" /> -->
                        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                    v-hasPermi="['system:checkplan:edit']" v-if="scope.row.planStatus == '1'">修改</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                    v-hasPermi="['system:checkplan:remove']"
                                    v-if="scope.row.planStatus == '1'">删除</el-button>
                                <el-button type="text" plain icon="el-icon-upload2" size="mini"
                                    @click="handleImport(scope.row, '下发')" v-hasPermi="['system:checkplan:editStatus']"
                                    v-if="scope.row.planStatus == '1'">下发</el-button>
                                <el-button type="text" plain icon="el-icon-download" size="mini"
                                    @click="handleImport(scope.row, '关闭')" v-hasPermi="['system:checkplan:editStatus']"
                                    v-if="scope.row.planStatus != '3'">关闭</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 添加或修改安检计划对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="计划名称" prop="planName">
                            <el-input v-model="form.planName" placeholder="请输入计划名称" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户类型" prop="type">
                            <el-select v-model="form.customerType" filterable placeholder="请选择" style='width:100%'>
                                <el-option v-for="dict in dict.type.customer_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="起止时间" prop="openDate">
                            <el-date-picker v-model="form.openDate" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="安检员" prop="checkerId">
                            <el-select v-model="form.checkerId" placeholder="请选择安检员" clearable style='width:100%'>
                                <el-option v-for="(item) in checkerNameList" :key="item.userId" :label="item.userName"
                                    :value="item.userId" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <el-row>
                <el-col :span="6">
                    <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                        :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                        @node-click="handleNodeClick" />
                </el-col>
                <el-col :span="18">
                    <el-card class="box-card" style="margin-top: 10px;height: 500px;overflow-y: auto;">
                        <el-form :model="queryParams1" ref="queryForm1" size="small" v-show="showSearch" label-width="68px">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="客户类型" prop="customerType">
                                        <el-select v-model="queryParams1.customerType" filterable placeholder="请选择">
                                            <el-option v-for="dict in dict.type.customer_type" :key="dict.value"
                                                :label="dict.label" :value="dict.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="客户名称" prop="customerName">
                                        <el-input v-model="queryParams1.customerName" placeholder="请输入客户名称" clearable />
                                    </el-form-item></el-col>
                                <!-- <el-col :span="5">
                                    <el-form-item label="客户地址" prop="customerAddress">
                                        <el-input v-model="queryParams.customerAddress" placeholder="请输入客户地址" clearable
                                            style="width: 150px" />
                                    </el-form-item></el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="手机号" prop="telephone">
                                        <el-input v-model="queryParams1.telephone" placeholder="请输入手机号" clearable />
                                    </el-form-item></el-col>

                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8" :offset="16">
                                    <el-form-item>
                                        <el-button type="primary" icon="el-icon-search" size="mini"
                                            @click="handleQuery1">搜索</el-button>
                                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                        <el-row style="display: flex;flex-direction: row;align-self: center;">
                            <el-col :span="11">
                                <el-table v-loading="loading" :data="userList1" border
                                    @selection-change="handleSelectionChange1" ref="Table1">
                                    <el-table-column type="selection" align="center" />
                                    <el-table-column label="客户名称" align="center" key="customerName" prop="customerName"
                                        :show-overflow-tooltip="true" />
                                    <el-table-column prop="status" label="客户类型" align="center">
                                        <template slot-scope="scope">
                                            <dict-tag :options="dict.type.customer_type" :value="scope.row.customerType" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="联系电话" align="center" key="telephone" prop="telephone"
                                        :show-overflow-tooltip="true" />
                                    <!--                                    <el-table-column prop="status" label="安检状态" align="center">-->
                                    <!--                                        <template slot-scope="scope">-->
                                    <!--                                            <span v-if="scope.row.status == 1">待安检</span>-->
                                    <!--                                            <span v-if="scope.row.status == 2">正常</span>-->
                                    <!--                                            <span v-if="scope.row.status == 3">隐患</span>-->
                                    <!--                                            <span v-if="scope.row.status == 4">到访不遇</span>-->
                                    <!--                                            <span v-if="scope.row.status == 5">拒绝安检</span>-->
                                    <!--                                            <span v-if="scope.row.status == 0">暂无</span>-->
                                    <!--                                        </template>-->
                                    <!--                                    </el-table-column>-->
                                    <el-table-column label="客户地址" align="center" key="customerAddress"
                                        prop="customerAddress" :show-overflow-tooltip="true" />

                                </el-table>

                                <pagination v-show="total1 > 0" size="small" :total="total1"
                                    :page.sync="queryParams1.pageNum" :limit.sync="queryParams1.pageSize"
                                    @pagination="getUserInfoList" :small="true" layout="total,prev,pager,next" />
                            </el-col>
                            <el-col :span="2">
                                <div class="table_transmission">
                                    <div class="table_transmission_img" @click="clearList()">
                                        <i class="el-icon-arrow-left"></i>
                                    </div>
                                    <div class="table_transmission_img" @click="giveList()">
                                        <i class="el-icon-arrow-right"></i>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="11">
                                <div style="width:100%;height: 500px;overflow-y: auto;">
                                    <el-table v-loading="loading" :data="userList2" border
                                        @selection-change="handleSelectionChange2">
                                        <el-table-column type="selection" align="center" />
                                        <el-table-column label="客户名称" align="center" key="customerName" prop="customerName"
                                            :show-overflow-tooltip="true" />
                                        <el-table-column prop="status" label="客户类型" align="center">
                                            <template slot-scope="scope">
                                                <dict-tag :options="dict.type.customer_type"
                                                    :value="scope.row.customerType" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="联系电话" align="center" key="telephone" prop="telephone"
                                            :show-overflow-tooltip="true" />
                                        <el-table-column label="客户地址" align="center" key="customerAddress"
                                            prop="customerAddress" :show-overflow-tooltip="true" />

                                    </el-table>
                                </div>

                            </el-col>
                        </el-row>

                    </el-card>
                </el-col>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { playInfo, addPlay, updatePlay, delPlay, playList, updatePlanStatus } from "@/api/security/plan.js"
import { customeList, customerBindingMeterList } from '@/api/fileManagement/civilArchives.js'
import { areaTreeList } from "@/api/fileManagement/areainfo.js"
import { listUser, } from "@/api/system/user";
export default {
    name: "areaDefinition",
    components: {},
    dicts: ["sys_normal_disable", "customer_type"],
    data() {
        return {
            checkerNameList: [], // 安检员
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            idName: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            total1: 0,
            // 小区表格数据
            userList: [],
            userList1: [],
            userList2: [],
            infoList: [],
            infoList1: [],
            // 弹出层标题
            title: "",
            // 企业树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 企业名称
            deptName: undefined,
            // 表单参数
            form: {
                openDate: [],

            },
            defaultProps: {
                children: "children",
                label: "label",
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: undefined,
                phonenumber: undefined,
                status: undefined,
                deptId: undefined,
            },
            queryParams1: {
                pageNum: 1,
                pageSize: 10,
                customerType: undefined,
                customerName: undefined,
                telephone: undefined,
            },
            // 表单校验
            rules: {
                planName: [
                    { required: true, message: "计划名称不能为空", trigger: "blur" },
                ],
                customerType: [
                    { required: true, message: "客户类型不能为空", trigger: "select" },
                ],
                checkerId: [
                    { required: true, message: "安检员不能为空", trigger: "select" },
                ],
            },
        };
    },
    watch: {
        // 根据名称筛选企业树
        deptName(val) {
            this.$refs.tree.filter(val);
        },
        form: {
            deep: true,
            handler(val) {
                this.form = val
            }
        },
        userLists1: {
            deep: true,
            handler(val) {
                this.userLists1 = val
            },
        }
    },
    created() {
        this.getList();
        this.getUserInfoList();
        this.getDeptTree();
    },
    methods: {
        // 下发-关闭
        handleImport(data, info) {
            let param = {
                planStatus: '',
                id: data.id
            }
            if (info == '下发') {
                param.planStatus = '2'
            } else {
                param.planStatus = '3'
            }

            this.$modal
                .confirm('是否确认' + info + data.planName + '?')
                .then(function () {
                    return updatePlanStatus(param)
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(info + "成功");
                })
                .catch(() => { });

        },

        /** 查询员工列表 */
        getuserList() {

            listUser({ pageNum: 1, pageSize: 9999 }).then((response) => {
                response.rows.map((res) => {
                    this.checkerNameList.push(res)
                })
            }
            )
        },
        /** 查询企业下拉树结构 */
        getDeptTree() {
            areaTreeList().then((response) => {
                this.deptOptions = response.data;

            });
        },
        giveList() {
            this.userList2 = this.infoList
        },
        clearList() {
            this.$refs.Table1.clearSelection()
            this.infoList1.map((res) => {
                this.userList2.map((item, index) => {
                    if (res.id === item.id) {
                        this.userList2.splice(index, 1)
                    }
                })
            })
        },
        handleSelectionChange1(selection) {
            let list = []
            list = [...selection, ...this.infoList]
            this.infoList = Array.from(new Set(list))
            console.log(this.infoList)
        },
        handleSelectionChange2(selection) {
            console.log(selection, 2222)
            this.infoList1 = selection
        },

        // /** 查询小区列表 */
        getList() {
            this.loading = true;
            playList(this.queryParams).then((res) => {
                console.log(res)
                this.loading = false;
                this.userList = res.rows
            })
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams1.areaId = data.id;
            this.getUserInfoList()
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: "0",
                remark: undefined,
                postIds: [],
                roleIds: [],

            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        //  新增搜索
        handleQuery1() {
            this.queryParams1.pageNum = 1
            this.getUserInfoList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.deptId = undefined;
            this.getList();
        },
        // 客户档案清楚
        resetQuery1() {
            this.resetForm("queryForm1");
            this.queryParams1.areaId = undefined;
            this.getUserInfoList()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.idName = selection.map((item) => item.planName);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd(info) {
            this.reset();
            console.log(info)
            if (info) {
                this.open = true;
                this.title = "新增计划";
                this.getuserList()
                this.userList2 = []
                this.checkerNameList = []
            }

        },
        // 获取客户信息
        getUserInfoList() {
            customerBindingMeterList(this.queryParams1).then((response) => {
                this.userList1 = response.rows;
                this.total1 = response.total;
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.checkerNameList = [];
            this.getuserList();
            playInfo(row.id).then((response) => {
                this.form = response.data;
                this.$set(this.form, 'openDate', [])
                this.form.openDate[0] = response.data.startTime
                this.form.openDate[1] = response.data.stopTime
                this.open = true;
                this.title = "修改小区";
                this.userList2 = []
                this.userList2 = JSON.parse(response.data.customerJson)
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let list = []
                    this.userList2.map((res) => {
                        console.log(res, 1111111)
                        let obj = {
                            id: res.id,
                            customerName: res.customerName,
                            customerType: res.customerType,
                            telephone: res.telephone,
                            customerAddress: res.customerAddress
                        }
                        list.push(obj)
                    })
                    let reault = JSON.stringify(list)
                    let param = {
                        checkerId: this.form.checkerId,
                        startTime: this.form.openDate[0],
                        stopTime: this.form.openDate[1],
                        customerType: this.form.customerType,
                        customerJson: reault,
                        planName: this.form.planName,
                    }
                    console.log(param)
                    if (this.form.id != undefined) {
                        param.id = this.form.id
                        updatePlay(param).then((res) => {
                            if (res.code == 200) {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.$modal.msgError(res.msg);
                                this.open = false;
                            }

                        });
                    } else {
                        if (this.userList2.length > 0) {

                            addPlay(param).then((res) => {
                                if (res.code == 200) {
                                    this.$modal.msgSuccess("新增成功");
                                    this.open = false;
                                    this.getList();
                                } else {
                                    this.$modal.msgError(res.msg);
                                    this.open = false;
                                }

                            });
                        } else {
                            this.$modal.msgError('请选择客户');
                        }

                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            let userIds = ''
            let userName = ''
            if (row == '批量') {
                userIds = this.ids.join(',')
                userName = this.idName.join(',')
            } else {
                userIds = row.id
                userName = row.planName
            }
            this.$modal
                .confirm('是否确认删除计划名称为"' + userName + '"的数据？')
                .then(function () {
                    return delPlay(userIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },

        /** 导出按钮操作 */
        handleExport() {
            let param = {
                id: this.ids
            }
            this.download(
                "/system/checkplan/export",
                {
                    ...this.queryParams, ...param
                },
                `user_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
<style>
.table_transmission {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .table_transmission_img {
        width: 50px;
        height: 30px;
        border-radius: 5px;
        background-color: #d26454;
        margin-bottom: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        cursor: pointer;
    }
}
</style>
